import { defineStore } from 'pinia';
import { ref } from 'vue';

// 检查是否在qiankun环境中
const isQiankunEnv = (window as any).__POWERED_BY_QIANKUN__;

export const useDashboardStore = defineStore(
  'dashboard',
  () => {
    // 顶部面板数据
    const topPanelData = ref([
      {
        title: 'pages.dashboardBase.topPanel.card1',
        number: '¥ 28,425.00',
        upTrend: '20.5%',
        leftType: 'echarts-line',
      },
      {
        title: 'pages.dashboardBase.topPanel.card2',
        number: '¥ 768.00',
        downTrend: '20.5%',
        leftType: 'echarts-bar',
      },
      {
        title: 'pages.dashboardBase.topPanel.card3',
        number: '1126',
        upTrend: '20.5%',
        leftType: 'icon-usergroup',
      },
      {
        title: 'pages.dashboardBase.topPanel.card4',
        number: 527,
        downTrend: '20.5%',
        leftType: 'icon-file-paste',
      },
    ]);

    // 图表数据缓存 - 使用对象而不是Map，便于序列化
    const chartDataCache = ref<Record<string, any>>({});

    // 获取或生成图表数据
    const getChartData = (key: string, generator: () => any) => {
      if (!chartDataCache.value[key]) {
        chartDataCache.value[key] = generator();
      }
      return chartDataCache.value[key];
    };

    // 清除缓存（用于重新生成数据）
    const clearCache = () => {
      chartDataCache.value = {};
    };

    // 更新顶部面板数据
    const updateTopPanelData = (index: number, data: any) => {
      if (topPanelData.value[index]) {
        topPanelData.value[index] = { ...topPanelData.value[index], ...data };
      }
    };

    // 在qiankun环境中，尝试从全局状态恢复数据
    if (isQiankunEnv && (window as any).__QIANKUN_PROPS__?.globalState) {
      const globalState = (window as any).__QIANKUN_PROPS__.globalState;
      const globalData = globalState.getGlobalState?.() || {};

      // 如果全局状态中有dashboard数据，使用它
      if (globalData.dashboardData) {
        topPanelData.value = globalData.dashboardData.topPanelData || topPanelData.value;
        chartDataCache.value = globalData.dashboardData.chartDataCache || chartDataCache.value;
      }

      // 监听全局状态变化
      globalState.onGlobalStateChange((state: any, prev: any) => {
        if (state.dashboardData) {
          topPanelData.value = state.dashboardData.topPanelData || topPanelData.value;
          chartDataCache.value = state.dashboardData.chartDataCache || chartDataCache.value;
        }
      });
    }

    return {
      topPanelData,
      chartDataCache,
      getChartData,
      clearCache,
      updateTopPanelData,
    };
  },
  {
    // 在qiankun环境中禁用持久化，避免沙箱隔离问题
    persist: isQiankunEnv
      ? false
      : {
          key: 'dashboard-store',
          storage: localStorage,
        },
  },
);
